#!/Users/hepeng/.pyenv/shims/python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/4 11:13 上午
# @Author  : hepeng
# @Site    : 
# @File    : CnfDomain.py

from __future__ import unicode_literals
import os
from utils.IniUtils import ConfigHanlder,configWriter
from utils.tools import cp_file

class CnfDomain(object):
    def __init__(self, cnf_path, main_db_domain, data_domain, bmc_install_domain):
        self._mysql_section = 'mysql'
        self._mysqld_section = 'mysqld'
        self._mysql_safe_section = 'mysqld_safe'
        self._socket_key = 'socket'
        self._pid_file_key = 'pid-file'
        self._data_dir_key = 'datadir'
        self._cnf_path = cnf_path
        self._confing_handler = ConfigHanlder(self._cnf_path)
        self._data_domain = data_domain
        self._main_db_domain = main_db_domain
        self._bmc_install_domain = bmc_install_domain

    @configWriter
    def cnf_content_handler(self):
        data_dir_path = self._data_domain.data_dir
        alias_name = self._main_db_domain.alias
        pid_file_path = os.path.join(self._data_domain.data_dir, alias_name + '.pid')
        sock_file_path = os.path.join(self._data_domain.data_dir, alias_name + '.sock')
        self._mysql_section_handler({self._socket_key: sock_file_path})
        self._mysqld_serction_handler({self._socket_key: sock_file_path, self._data_dir_key: data_dir_path})
        self._mysql_safe_section_handler({self._pid_file_key: pid_file_path})

    def _mysql_safe_section_handler(self, pid_file_dict):
        """
        修改mysql_safe pid-file
        :param pid_file:
        :return:
        """
        self._confing_handler.updata_value_plus(self._mysql_safe_section, pid_file_dict)

    def _mysql_section_handler(self, sock_path_dict):
        """
        修改 sock 文件，在mysql标签
        :param sock_path:
        :return:
        """
        self._confing_handler.updata_value_plus(self._mysql_section, sock_path_dict)

    def _mysqld_serction_handler(self, scok_data_dir):
        """
        修改mysqld 中的sock_path ,data_dir
        :param sock_path:
        :param data_dir:
        :return:
        """
        self._confing_handler.updata_value_plus(self._mysqld_section, scok_data_dir)

    def cp_cnf(self, dest_dir='/etc'):
        src_file = self._bmc_install_domain.cnf_path()
        cnf_file_name = os.path.basename(src_file)
        if cnf_file_name != 'my.cnf':
            cnf_dir_path = os.path.dirname(src_file)
            mod_src_file = os.path.join(cnf_dir_path, 'my.cnf')
            os.rename(src_file, mod_src_file)
        cp_file(src_file, dest_dir)
